express = require 'express'
multer  = require 'multer'
mkdirp = require 'mkdirp'

zlib = require 'zlib'
fstream = require 'fstream'
tar = require 'tar'
path = require 'path'
fs = require 'fs'
mime = require 'mime'
serveIndex = require 'serve-index'
_config = require './config'
_utils = require './utils'

TMPDIR = _config.tmp
DESTDIR = _config.dest

mkdirp.sync(TMPDIR)
mkdirp.sync(DESTDIR)

app = express()

app.use(multer({dest: TMPDIR}))
app.use(express.static(DESTDIR))

###
  文件上传
###
app.post('/upload', (req, resp)->
  extractor = tar.Extract({path: DESTDIR})
    .on('error', ()->)
    .on('end', ()->)

  fstream.Reader(req.files.attachments.path)
    .pipe(zlib.Gunzip())
    .pipe(extractor)
    .on('close', -> _utils.clearDir(TMPDIR))

  resp.sendStatus(200)
)

app.use('/', serveIndex(DESTDIR, {'icons': true}))

###
  文件上传前的md5校验分析，避免重复上传
###

app.get('/upload/:project/md5', (req, resp)->

)
app.listen _config.port